<?php

require_once('conf/DBConnection.php');
require_once('dao/DAO.php');


/**
 * DAO is actually a J2EE  pattern. 
 * It can easily be implemented in PHP and helps greatly in separating database access from the rest of your code. 
 * The DAOs form a thin layer. The DAO layer can be 'stacked' which helps for instance if you want to add DB 
 * caching later when tuning your application. You should have one DAO class for every VO class. 
 * Naming conventions are a good practice. 
 * 
 * @author dintech
 *
 */

class UsuarioDAO extends DAO {

	function UsuarioDAO() {}

	function get($id) {
		DBConnection::getInstance();
		$query = "SELECT * FROM `users` where $id = id";
		$result = mysql_query($query);
		$results = $this->getFromResult($result);
		return $results[0];
	}

	function getByUsername($username) {
		DBConnection::getInstance();
		$query = "SELECT * FROM `users` where '$username' = username";
		$result = mysql_query($query);
		$results = $this->getFromResult($result);
		return $results[0];
	}
	
	function find($criteria){
		DBConnection::getInstance();
		$conditions = $this->getConditions($criteria);
		$query = "SELECT * FROM `users` where rol<>'0' $conditions";
		$result = mysql_query($query);	
		return $this->getFromResult($result);
	}
	
	function delete($id) {
		DBConnection::getInstance();
		$query = "DELETE from `users` where id = $id";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function update($vo) {
		DBConnection::getInstance();
		$passw = $vo->getPassw();
		
		if (($passw != null) && ($passw != "")) {
			// actualiza el rol
			$query = "UPDATE users SET ".
		            " passw = '".$vo->getPassw()."'".
					" WHERE id =".$vo->getId();
		} else {
			// actualiza solo el passw
			$query = "UPDATE users SET ".
						" rol = '".$vo->getRol()."'".
						" WHERE id =".$vo->getId();			
		}
		//echo $query;
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function insert(&$vo) {
		DBConnection::getInstance();
		$query = "INSERT INTO `users` (`id`, `username`, `passw`, `rol`) values (NULL,'".$vo->getUsername()."', '".$vo->getPassw()."', '".$vo->getRol()."' )";
		//echo $query;
		$result = mysql_query($query);
		return parent::checkError($result);
	}
	
	function getConditions($criteria){
		$conditions = parent::getConditionsAbs($criteria,'users');
		if ($criteria->getUsername() != null){
			$conditions.= " AND username = '".$criteria->getUsername()."'";
		}
	    if ($criteria->getRol() != null){
			$conditions.= " AND rol = ".$criteria->getRol();
		}
		return $conditions; 
	}
	
	function changePassword($username, $oldpassword, $newpassword) {
		$user = UsuarioDAO::getByUsername($username);
	}
	
}
?>